package com.jxtc.enterprise.hr.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.jxtc.enterprise.common.entity.Company;
import com.jxtc.enterprise.common.entity.Department;
import com.jxtc.enterprise.common.exception.ModifyFailureException;
import com.jxtc.enterprise.common.mapper.CompanyMapper;
import com.jxtc.enterprise.common.mapper.DepartmentMapper;
import com.jxtc.enterprise.hr.dto.DepartmentDTO;
import com.jxtc.enterprise.hr.dto.DepartmentUpdateDTO;
import com.jxtc.enterprise.hr.vo.DepartmentVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class HrDepartmentManagementService {

    private final DepartmentMapper departmentMapper;
    private final CompanyMapper companyMapper;

    /**
     * 根据公司 ID 查询该公司下所有的部门信息
     *
     * @param companyId 公司 ID
     * @return 返回部门信息列表
     */
    public List<DepartmentVO> listDepartmentByCompanyId(String companyId) {
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        wrapper.eq("company_id", companyId);
        List<Department> departments = departmentMapper.selectList(wrapper);

        return departments.stream().map(DepartmentVO::new).collect(Collectors.toList());
    }

    /**
     * 新增部门信息
     *
     * @param dto 部门信息 DTO
     * @return 返回新增的部门信息（部门 ID）
     */
    public DepartmentVO saveDepartment(DepartmentDTO dto) {
        QueryWrapper<Company> wrapper = new QueryWrapper<>();
        wrapper.eq("id", dto.getCompanyId());
        wrapper.eq("del_flag", 0);
        if (!companyMapper.exists(wrapper)) {
            throw new IllegalArgumentException("新增部门信息失败，公司 ID 不存在");
        }

        Department department = new Department();
        department.setCompanyId(dto.getCompanyId());
        department.setName(dto.getName());
        department.setAddress(dto.getAddress());

        if (departmentMapper.insert(department) > 0) {
            return new DepartmentVO(department);
        }

        throw new ModifyFailureException("新增部门信息失败，请稍后重试");
    }

    /**
     * 根据部门 ID 更新部门信息
     *
     * @param dto 包含部门 ID 的部门信息
     */
    public void updateDepartmentById(DepartmentUpdateDTO dto) {
        Department department = new Department();
        department.setId(dto.getId());

        if (dto.getName() != null && !dto.getName().isEmpty()) {
            department.setName(dto.getName());
        }
        if (dto.getAddress() != null && !dto.getAddress().isEmpty()) {
            department.setAddress(dto.getAddress());
        }

        if (departmentMapper.updateById(department) > 0) {
            return;
        }

        throw new ModifyFailureException("更新部门信息失败，请稍后重试");
    }

    /**
     * 根据部门 ID 删除部门信息（硬删除）
     *
     * @param id 部门 ID
     */
    public void deleteDepartmentById(String id) {
        if (departmentMapper.deleteById(id) > 0) {
            return;
        }

        throw new ModifyFailureException("删除部门信息失败，请稍后重试");
    }

    /**
     * 当前 PC 管理端，HR端 页面上，没有为各个部门单独提供配置取餐地址的输入框，当前 每个公司只有有个 取餐地址，
     * 此方法临时用于修复bug；当前 通过 PC管理端和HR页面，修改取餐地址后，department 表中的取餐地址没有被刷新，而用户小程序展示的取餐地址，是来之部门表，且下单时订单中的取餐地址信息，是来自部门表
     * 当前逻辑会导致 通过PC管理端，HR端对公司取餐地址的修改，无法生效
     * @param companyId
     * @param address
     */
    public void batchUpateDepartPickUpAddress(String companyId, String address) {

        int updatedCount = departmentMapper.update(new UpdateWrapper<Department>().eq("company_id", companyId).set("address", address));
        log.info("更新公司 {} 取餐地址为 {}, 同时更新公司所有部门的取餐地址, 共更新 {} 个部门", companyId, address, updatedCount);
    }
}
